package com.zhou.base.gateway.filter;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.zhou.base.gateway.properties.BackendPathProperites;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR;

/**
 * @author 18576666986
 * @description
 * @createDate 2022/9/9 11:22
 */

@Slf4j
public class RewriteBackendContextPathGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private BackendPathProperites backendPathProperites;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("custom global filter");
        Map<String, Object> attributes = exchange.getAttributes();
        Map<String, String> uriTemplateVariables = ServerWebExchangeUtils.getUriTemplateVariables(exchange);
        Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
        String host = route.getUri().getHost();
        if (backendPathProperites.getMaps() != null) {
            String prefix = backendPathProperites.getMaps().get(host);
            if (StringUtils.isNotEmpty(prefix)) {
                ServerHttpRequest req = exchange.getRequest();
                String newPath = prefix + req.getURI().getRawPath();
                ServerHttpRequest request = req.mutate().path(newPath).build();
                exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, request.getURI());
                if (log.isTraceEnabled()) {
                    log.trace("Prefixed URI with: " + prefix + " -> " + request.getURI());
                }
                return chain.filter(exchange.mutate().request(request).build());
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 10000;
    }
}
